/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package backingbeans;

import entities.Genre;
import entities.Music;
import java.io.Serializable;
import java.util.List;
import javax.ejb.EJB;
import javax.el.ExpressionFactory;
import javax.el.MethodExpression;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import org.primefaces.component.menuitem.MenuItem;
import org.primefaces.model.DefaultMenuModel;
import org.primefaces.model.MenuModel;
import sessions.GenreManager;
import sessions.MusicManager;

/**
 *
 * @author Antoine Boulinguez et Shyn-Yuan Cheng
 */
@ManagedBean(name="menuGenre")
@ViewScoped
public class MenuGenre implements Serializable {
    @EJB
    private MusicManager musicManager;
    @EJB
    private GenreManager genreManager;
    private String selectedGenreId;
    private MenuModel model;
    

    public MenuGenre() {
        // Create menu model
        model = new DefaultMenuModel();
    }

    public MenuModel getModel() {
        // Get genres and add a menu item for each
        List<Genre> lGenres = genreManager.getAllGenres();
        for (Genre g : lGenres) {
            MenuItem item = new MenuItem();
            item.setValue(g.getLabel());
            //item.setUrl("songsByGenre.xhtml?faces-redirect=true&amp;includeViewParams=true");
            ExpressionFactory factory = FacesContext.getCurrentInstance().getApplication().getExpressionFactory();
            MethodExpression methodsexpression = factory.createMethodExpression(
                    FacesContext.getCurrentInstance().getELContext(), 
                    "#{menuGenre.displayGenre(" + g.getId() + ")}", 
                    String.class, new Class[]{ActionEvent.class});
            item.setActionExpression(methodsexpression);
            model.addMenuItem(item);
        }
        
        return model;
    }

    public String getSelectedGenreId() {
        return selectedGenreId;
    }

    public void setSelectedGenreId(String selectedGenreId) {
        this.selectedGenreId = selectedGenreId;
    }
    
    public Genre getSelectedGenre() {
        try {
            return genreManager.getGenre(Long.valueOf(selectedGenreId));
        }
        catch(Exception e) {
            return null;
        }
    }
    
    public String displayGenre(String genreId) {
        this.selectedGenreId = genreId;
        return "genredisplay.xhtml?faces-redirect=true&amp;includeViewParams=true";
    }
    
    public List<Music> getMusicsByGenre() {
        Genre genre = getSelectedGenre();
        return musicManager.getMusics(genre);
    }
}
